package a.codetop.单调栈;


import java.util.Stack;

public class 移除k个数结果最小_402 {

    public String removeKdigits(String num, int k) {
        char[] c = num.toCharArray();
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < c.length; i++) {
            int x = Integer.parseInt(c[i]+"");
            //栈空:直接压入
            if(stack.isEmpty()){
                if(stack.isEmpty() && x==0)continue;//去前导0
                stack.push(x);
            }
            //栈不空:小的尽量往前顶（只有k次的调整能力）
            else {
                while(!stack.isEmpty()&&x<stack.peek() && k>0){
                    stack.pop();
                    k--;
                    //(1)k若提前=0: 只能按顺序压后面的..
                }
                if(stack.isEmpty() && x==0)continue;//去前导0
                stack.push(x);
            }
        }

        //(2)k还剩: 那我可不客气了，直接扔后几位
        while(k>0 && !stack.isEmpty()){
            stack.pop();
            k--;
        }

        //正向遍历栈
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < stack.size(); i++) {
            sb.append(stack.get(i));
        }
        String res = sb.toString();
        if(res.length()==0)return "0";//特
        return res;
    }

}
